package com.etop.weibo.servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etop.weibo.dao.DAOFactory;
import com.etop.weibo.beans.Comment;
import com.etop.weibo.beans.Say;
import com.etop.weibo.beans.Secret;
import com.etop.weibo.beans.StarAndFan;
import com.etop.weibo.beans.User;
import com.etop.weibo.util.WeiBoException;

public class operationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String operation = req.getParameter("operation");
		if (operation != null) {
			switch (operation) {
			case "登陆":
				login(req, resp);
				break;
			case "登出":
				logout(req, resp);
				break;
			case "注册":
				registration(req, resp);
				break;
			case "私信":
				createSecret(req, resp);
				break;
			case "发送私信":
				sendSecret(req, resp);
				break;
			case "待关注列表":
				showMayStarList(req, resp);
				break;
			case "关注":
				focus(req, resp);
				break;
			case "关注列表":
				showStarsList(req, resp);
				break;
			case "粉丝列表":
				showFansList(req, resp);
				break;
			case "取消关注":
				unfocus(req, resp);
				break;
			case "发布":
				publish(req, resp);
				break;
			case "删除微博":
				deleteWeibo(req, resp);
				break;
			case "评论":
				comment(req, resp);
				break;
			case "删除评论":
				deleteComment(req, resp);
				break;
			case "返回主页":
				backMain(req, resp);
				break;
			case "转向评论页":
				toComment(req, resp);
				break;
			default:
				WeiBoException e = new WeiBoException("错误操作！");
				toError(req, resp, e);
				break;
			}
		}
	}

	
	//登陆
	public void login(HttpServletRequest req, HttpServletResponse resp) {
		User user = null;
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		boolean blank = false;
		if(username == null || "".equals(username.trim())){
			req.setAttribute("username_blank", true);
			blank = true;
		}
		if(password == null || "".equals(password.trim())) {
			req.setAttribute("password_blank", true);
			blank = true;
		}
		if(blank){
			RequestDispatcher rd = this.getServletContext()
					.getRequestDispatcher("/unadmin/login.jsp");
			try {
				rd.forward(req, resp);
				return;
			} catch (ServletException | IOException e1) {
				e1.printStackTrace();
			}
		}
		
		try {
//			user = DAOFactory.getUserDao().login(username,password);
                        req.getSession().setAttribute("user", user);
			backMain(req, resp);
			return;
		} catch (WeiBoException e) {
			toError(req, resp, e);
			return ;
		}
	}
	
	//登出
	public void logout(HttpServletRequest req, HttpServletResponse resp){
		HttpSession session = req.getSession();
		session.setAttribute("user", null);
		
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/unadmin/login.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}
	
	//注册
	public void registration(HttpServletRequest req, HttpServletResponse resp){
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		boolean blank = false;
		if(username == null || "".equals(username.trim())){
			req.setAttribute("username_blank", true);
			blank = true;
		}
		if(password == null || "".equals(password.trim())) {
			req.setAttribute("password_blank", true);
			blank = true;
		}
		if(blank){
			RequestDispatcher rd = this.getServletContext()
					.getRequestDispatcher("/unadmin/registration.jsp");
			try {
				rd.forward(req, resp);
				return;
			} catch (ServletException | IOException e1) {
				e1.printStackTrace();
			}
		}
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setNickname(req.getParameter("nickname"));
		user.setSex(req.getParameter("sex"));
		user.setIntroduction(req.getParameter("introduction"));
		
		try{
			DAOFactory.getUserDao().add(user);
			resp.sendRedirect(req.getServletContext().getContextPath() + "/unadmin/registrationSuccessful.jsp");
			return;
		} catch(WeiBoException e){
			toError(req, resp, e);
			return ;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//私信
	public void createSecret(HttpServletRequest req, HttpServletResponse resp){
		try {
			DAOFactory.getUserDao().load(Integer.parseInt(req.getParameter("withWhoseId")));
		} catch(WeiBoException e){
			toError(req, resp, new WeiBoException("私信对象不存在！！！"));
			return;
		}
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/admin/showSecret.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}
	
	//发送私信
	public void sendSecret(HttpServletRequest req, HttpServletResponse resp){
		HttpSession session = req.getSession();
		User user = (User)session.getAttribute("user");
		
		Secret secret = new Secret();
		secret.setFromId(user.getId());
		secret.setToId(Integer.parseInt(req.getParameter("withWhoseId")));
		secret.setWhat(req.getParameter("what"));

		DAOFactory.getSecretDao().add(secret);
		createSecret(req, resp);
		return;
	}
	
	//关注
	public void focus(HttpServletRequest req, HttpServletResponse resp) {
		StarAndFan starAndFan = new StarAndFan();
		User user = (User) req.getSession().getAttribute("user");
		starAndFan.setFanId(user.getId());
		starAndFan.setStarId(Integer.parseInt(req.getParameter("starId")));
		try{
			DAOFactory.getStarAndFanDao().add(starAndFan);
			showMayStarList(req, resp);
			return;
		} catch(WeiBoException e){
			toError(req, resp, e);
			return ;
		}
	}
	
	//显示待关注列表
	public void showMayStarList(HttpServletRequest req, HttpServletResponse resp) {
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/admin/showMayStarList.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}
	
	//取消关注
	public void unfocus(HttpServletRequest req, HttpServletResponse resp){
		User user = (User) req.getSession().getAttribute("user");
		int fanId = user.getId();
		int starId = Integer.parseInt(req.getParameter("starId"));
		try {
			DAOFactory.getStarAndFanDao().delete(starId, fanId);
			showStarsList(req, resp);
			return;
		} catch(WeiBoException e){
			toError(req, resp, e);
			return;
		}
	}
	
	//显示关注列表
	public void showStarsList(HttpServletRequest req, HttpServletResponse resp){
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/admin/showStarsList.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}

	//显示粉丝列表
	public void showFansList(HttpServletRequest req, HttpServletResponse resp){
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/admin/showFansList.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}
	
	//发布微博
	public void publish(HttpServletRequest req, HttpServletResponse resp){
		User user = (User)req.getSession().getAttribute("user");
		Say say = new Say();
//		say.setWhoId(user.getId());
		say.setWhat(req.getParameter("publish-input"));
		DAOFactory.getSayDao().add(say);
		backMain(req, resp);
		return;
	}
	
	//删除微博
	public void deleteWeibo(HttpServletRequest req, HttpServletResponse resp){
		HttpSession session = req.getSession();
		User user = (User)session.getAttribute("user");
		int id = Integer.parseInt(req.getParameter("sayId"));
		Say say = DAOFactory.getSayDao().load(id);
                
		if(say == null) {
			toError(req, resp, new WeiBoException("删除失败，微博不存在！！！"));
			return;
		}
//		if(say.getWhoId() == user.getId()){
//			DAOFactory.getCommentDao().deleteAll(id);
//			DAOFactory.getSayDao().delete(id);
//			backMain(req, resp);
//			return;
//		} else {
//			toError(req, resp, new WeiBoException("非本人操作！不可删除！！！"));
//			return ;
//		}
	}
	
	//评论
	public void comment(HttpServletRequest req, HttpServletResponse resp){
		int sayId = Integer.parseInt(req.getParameter("sayId"));
		if(DAOFactory.getSayDao().load(sayId) == null) {
			toError(req, resp, new WeiBoException("评论失败，该微博不存在！！！"));
			return;
		}
		User user = (User)req.getSession().getAttribute("user");
		Comment comment = new Comment();
//		comment.setWhoId(user.getId());
//		comment.setOnId(sayId);
		comment.setWhat(req.getParameter("what"));
		DAOFactory.getCommentDao().add(comment);
		toComment(req, resp);
		return;
	}
	
	//删除某条评论（仅限本人操作）
	public void deleteComment(HttpServletRequest req, HttpServletResponse resp){
		int id = Integer.parseInt(req.getParameter("commentId"));
		try {
			DAOFactory.getCommentDao().delete(id);
		} catch(WeiBoException e){
			toError(req, resp, e);
			return;
		}
		toComment(req, resp);
		return;
	}
	
	//返回主页
	public void backMain(HttpServletRequest req, HttpServletResponse resp){
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/admin/show_fromLZH/weibo.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}
	
	//转到评论页
	public void toComment(HttpServletRequest req, HttpServletResponse resp){
		int sayId = Integer.parseInt(req.getParameter("sayId"));
		Say say = null;
		int theUserId = Integer.parseInt(req.getParameter("theUserId"));
		try {
			say = DAOFactory.getSayDao().load(sayId);
		} catch(WeiBoException e){
			toError(req, resp, new WeiBoException("跳转失败，该微博不存在!!!"));
			return;
		}
//		if(say.getWhoId() != theUserId) {
//			toError(req, resp, new WeiBoException("未知错误，请重试！！！"));
//			return;
//		}
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/admin/showComment.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}
	
	//转向错误提示页
	public void toError(HttpServletRequest req, HttpServletResponse resp, WeiBoException e){
		req.setAttribute("err_msg", e.getMessage());
		RequestDispatcher rd = this.getServletContext()
				.getRequestDispatcher("/unadmin/error.jsp");
		try {
			rd.forward(req, resp);
			return;
		} catch (ServletException | IOException e1) {
			e1.printStackTrace();
		}
	}
}
